<?php
/**
 * 用户管理
 */
declare (strict_types = 1);

namespace app\api\controller;

use app\validate\Users as UserValidate;
use think\Exception;
use think\facade\Db;
use think\Request;
use think\Response;
use think\response\Json;

class Users
{
    /**
     * 显示资源列表
     *
     * @return Response
     */
    public function index(Request $request): Response
    {
        $params = $request->get();
        $page = (int)$params['pageNum'];
        $pageSize =(int)$params['pageSize'];
        try {
            $if = array();
            if (isset($params['keywords']) && !empty($params['keywords'])) {
                $if[] = ['nickname', 'like', '%' . $params['keywords'] . '%'];
            }
            if (isset($params['status'])) {
                $if[] = ['status', '=', $params['status']];
            }
            if (isset($params['type'])) {
                $if[] = ['type', '=', $params['type']];
            }

            $field = ['id', 'mobile', 'nickname', 'status', 'type', 'gender', Db::raw("FROM_UNIXTIME(create_time, '%Y-%m-%d %H:%i:%s') AS createTime")];

            $roles = Db::name('user')->where($if)->field($field)->paginate(['page' => $page, 'list_rows' => $pageSize]);
//            return Db::getLastSql();
            $sourceData = $roles->items();
            $accounts = array_map(function ($item) {
                if ($item['gender'] == 1) {
                    $item['genderLabel'] = '男';
                } else {
                    $item['genderLabel'] = '女';
                }
                return $item;
            }, $sourceData);;
            return success([
                'total' => $roles->total(),
                'list' => $accounts,
                'current_page' => $roles->currentPage(),
                'last_page' => $roles->lastPage(),
            ]);
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return error([], 9008, '系统错误');
        }
    }

    /**
     * 显示创建资源表单页.
     *
     * @return Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param Request $request
     * @return Response
     */
    public function save(Request $request): Response
    {
        //
        $validate = new UserValidate();

        $data = $request->post();
      
        // 校验数据
        if (!$validate->check($data)) {
            return error([], 9001, $validate->getError());
        }

        // 执行新增操作
        // 把手机号作为用户字段存储
        $updateData['mobile'] = $data['mobile'];
        // 设置初始密码
        $updateData['password'] = initPassword();
        $updateData['create_time'] = time();

        $result = Db::name('user')->save($updateData);
        if ($result !== false) {
            return success([], 0, '新增用户成功');
        } else {
            return error([], 9004, '新增用户失败');
        }
    }

    /**
     * 显示指定的资源
     *
     * @param    $id
     * @return Response
     */
    public function read($id): Response
    {
        //
        $data = Db::name('user')->alias('user')->leftJoin('role','user.role=role.id')->field(['user.*','role.name as rolename',Db::raw("FROM_UNIXTIME(create_time, '%Y-%m-%d %H:%i:%s') AS createTime")])->where('user.id','=',$id)->find();
        return success($data);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param    $id
     * @return Response
     */
    public function edit($id, Request $request): Response
    {
        $validate = new UserValidate();

        $data = $request->post();
        // 校验数据
        if (!$validate->check($data)) {
            return error([], 9001, $validate->getError());
        }
        // 执行修改操作
        $data['mobile'] = $data['mobile'];
        // 设置初始密码
        $data['password'] = initPassword();
        $data['create_time'] = time();

        $result = Db::name('user')->strict(false)->save($data);
        if ($result !== false) {
            return success([], 0, '修改用户成功');
        } else {
            return error([], 9004, '修改用户失败');
        }
    }

    /**
     * 保存更新的资源
     *
     * @param Request $request
     * @param int $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param    $id
     * @return Response
     */
    public function delete($id)
    {
        //
    }

    /**
     * 重置密码
     * @param $id
     * @param Request $request
     * @return Json
     */
    public function reset($id, Request $request): Json
    {
        $data = $request->request();
        if (isset($data['password']) && !empty($data['password'])) {
            // 执行 修改操作
            $updateData['id'] = $id;
            $updateData['update_time'] = time();
            $updateData['password'] = initPassword($data['password']);
            $result = Db::name('user')->save($updateData);

            if ($result !== false) {
                return success([], 0, '重置密码成功');
            } else {
                return error([], 9003, '重置密码失败');
            }
        } else {
            return error([], 9004, '密码不能为空');
        }
        return $id;
    }

    public function admin(Request $request)
    {
        $cache = $request->cache;
        $roles = Db::name('role')->where('id', '=', $cache['role'])->find();
//        return Db::getLastSql();
        if ($roles == null) {
            return error([], 9009, '您没有登录权限，请联系平台管理员');
        }
        $perms = Db::name('menu')->where('type', '=', 'BUTTON')->where('id', 'in', implode(',', json_decode($roles['menus'], true)))->select()->toArray();
        $response = array(
            'avatar' => 'https://foruda.gitee.com/images/1723603502796844527/03cdca2a_716974.gif',
            'nickname' => $cache['nickname'],
            'roles' => [$roles['code']],
            'userId' => $cache['id'],
            'username' => $cache['mobile'],
            'type' => [1 => 'ADMIN', 2 => "AGENT", 3 => "INSTITUTION"][$cache['type']]
        );
        $permsArray = array();
        foreach ($perms as $item) {
            $permsArray[] = $item['perm'];
        }
        $response['perms'] = $permsArray;
        return success($response);
    }

    public function options(Request $request)
    {
        $roleCode = ['ADMIN', 'AGENT'];
        $data = Db::name('user')->alias('account')->join('role', 'role=role.id')->where('role.code', 'in', $roleCode)->field('account.id as value,nickName as label')->select();
        return success($data);
    }

    /** 校验用户是否被注册过
     * @param $account
     * @param Request $request
     * @return Json
     */
    public function checkUnique($account, Request $request): Json
    {
        $id = $request->get('id') ?: '';
        $service = app('app\service\checkField');
        $result = $service->accountCheckUnique($account, $id);
//        $result = Db::name('user')->where(['account'=>$account])->count();
        return success(['isUnique' => $result]);
    }

    /**
     * 校验手机号是否注册过
     * @param $phone
     * @param Request $request
     * @return Json
     */
    public function checkPhone($phone, Request $request): Json
    {
        $id = $request->get('id') ?: '';
        $service = app('app\service\checkField');
//         $result = Db::name('user')->where(['phone'=>$phone])->count();
        $result = $service->accountCheckPhone($phone, $id);
        return success(['isUnique' => $result]);
    }

    /**
     * @param Request $request
     * @return void
     */
    public function  editPassword(Request $request){
        $cache = $request->cache;
        $params = $request->post();
        try{
            $oldPassword = initPassword($params['oldPassword']);
            $check = Db::name('user')->where(['id'=>$cache['id'],'password'=>$oldPassword])->find();
            if(!empty($check)){
                $newPassword=$params['newPassword'];
                $confirmPassword= $params['confirmPassword'];
                if($newPassword!=$confirmPassword){
                    throw new Exception('两次密码不一致',9004);
                }
                $update = Db::name('user')->update(['id'=>$cache['id'],'password'=>initPassword($newPassword)]);
                if($update!==false){
                    writeLogToDb('修改密码成功',$cache['id'],1,['old'=>$params['oldPassword']]);
                    return success();
                }else{
                    throw new Exception('修改密码失败',9003);
                }
            }else{
                throw new Exception('原密码错误',9005);
            }
        }catch (\Exception $e){
            writeLogToDb('修改密码失败',$cache['id'],1,['message'=>$e->getMessage()]);
            return error([],$e->getCode()?:9006,$e->getMessage());
        }
    }
}
